package com.yan.network;


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.client.methods.HttpRequestBase;

import com.yan.activity.Article;
import com.yan.activity.Debug;



public class ResponseBuilder {
	private final static String TAG = "REPONSE_BUILDER";



	public static List<Article> getPopularOrLatestArticles(HttpRequestBase request) throws Exception{
		String response = new String(getData(request));
		Debug.debugTemporary(TAG, "getPopularOrLatestFilms response = "+response.replace(",", ",\n"));
		if(response == null){
			return null;
		}
		return ParsingManager.buildFilmsList(response);
	}
	
	
	public static List<Article> getArticles(HttpRequestBase request) throws Exception{
		String response = new String(getData(request));
		if(response == null){
			return null;
		}
		return ParsingManager.buildArticlesList(response);
	}
	
	

	/*public static Article getArticleDetails(HttpRequestBase request) throws Exception{
		String response = new String(getData(request));
		Debug.debugTemporary(TAG, "getFilmDetails response = "+response.replace(",", ",\n"));
		if(response == null){
			Debug.debugWarning(TAG, "getFilmDetails response == null");
			return null;
		}
		return ParsingManager.buildFilmDetailed(response);
	}*/

	

	
	private static byte[] getData (HttpRequestBase httpRequest) throws Exception{
		try {        
			HttpResponse response = HttpConnector.getHttpResponse(httpRequest);
			int responseCode = response.getCode();
			
			if(responseCode == HttpCode.OK){
				response.readBody();
			}
			else{
				response.close();
				throw new Exception("HTTP request failed [" + responseCode + "]"/*, CommunicationException.HTTP_ERROR*/);
			}
			byte[] data = response.getByteContent();
			response.close();
			return data;
        }
        catch (Exception e){
            e.printStackTrace();
            throw new Exception ("HTTP request failed"/*, CommunicationException.HTTP_ERROR*/);
        }
	 }
	
	
	/*
	 * This method creates an HTTP connection with the remote RSS host pointed by the user-specified
	 * URL and returns the server's response as a stream of XML data.
	 */
	public static InputStream getRSSData(HttpRequestBase httpRequest) {

		try {
			URL url = httpRequest.getURI().toURL();

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				return is;
			} else {
				return null;
			}
		} catch (Exception e) {

			return null;
		}

	}
	
	

}
